
import React from 'react';
import './brand.scss';
import SelectType from 'views/component/selectType';
import XDate from 'xdate';
import { ShopApi } from 'js/api/shop';
import echarts from 'js/lib/echarts';
import $ from 'jquery';
import { Link } from 'react-router';
import { Popup, PickerView } from 'antd-mobile';

const timeData = [{ id: 'day', name: '日' }, { id: 'month', name: '月' }, { id: 'season', name: '季' }, { id: 'year', name: '年' }];
let chartFontSize = parseInt(window.fontSize / 4);

const SelectNode = React.createClass({
    render() {
        let data = [[
            {
                label: '排名:由高到低',
                value: 1,
            },
            {
                label: '排名:由低到高',
                value: 2,
            },
            {
                label: '升降:由高到低',
                value: 3,
            },
            {
                label: '升降:由低到高',
                value: 4,
            }
        ]];

        return (
            <PickerView
                onChange={this.props.onChange}
                value={[this.props.value]}
                data={data}
                cols={1}
                cascade={false}
            />
        )
    }
});


const Brand = React.createClass({
    getInitialState() {
        return { TimeType: 'day', CurrDate: new XDate().toString('yyyy-MM-dd'), orderType: 1, brandData: [] }
    },
    componentDidMount() {
        this.getAllBrandsFlow();
    },
    getAllBrandsFlow() {
        let query = {
            ShopId: this.props.params.shopId,
            CurrDate: this.state.CurrDate,
            TimeType: this.state.TimeType,
            AreaTypeId: 8
        }
        ShopApi.getAllBrandsFlow(query, (data) => {
            if (data.length === 0) {
                return;
            }
            this.handleData(data);
        })
    },
    handleData(data) {
        var brandDataByName = {},
            id,
            len = 0,
            brandData = [],
            total = 0,
            timeType = this.state.TimeType,
            currDate = this.state.CurrDate;
        for (var i in data) {
            id = data[i].AREAID
            if (!brandDataByName[id]) {
                brandDataByName[id] = [];
            }
            if (timeType === 'season') {
                var year = data[i].YEAR
                var seasonIndex = data[i].CTIME
                if (new Date(year + ' ' + ((parseInt(seasonIndex) - 1) * 3 + 1)).getTime() > new Date().getTime()) {
                    continue
                }
            }
            brandDataByName[id].push(data[i])
        }
        for (var i in brandDataByName) {
            brandData.push(brandDataByName[i])
        }
        if (brandData[0].length > 0) {
            for (var i in brandData) {
                total += parseInt(brandData[i][brandData[i].length - 1].CDATA);
            }
            brandData.sort(function (a1, a2) {
                return parseInt(a1[a1.length - 1].CDATA) < parseInt(a2[a2.length - 1].CDATA)
                    ? 1
                    : -1
            });
            var j = 1;
            for (var i in brandData) {
                brandData[i][brandData[i].length - 1]['rank'] = j;
                j += 1;
                if (total === 0) {
                    brandData[i][brandData[i].length - 1]['per'] = 0
                } else {
                    brandData[i][brandData[i].length - 1]['per'] = (parseInt(brandData[i][brandData[i].length - 1].CDATA) / total * 100).toFixed(1)
                }
            }
        }
        if (brandData[0].length > 1) {
            brandData.sort(function (a1, a2) {
                return parseInt(a1[a1.length - 2].CDATA) < parseInt(a2[a2.length - 2].CDATA)
                    ? 1
                    : -1
            });
            var j = 1;
            for (var i in brandData) {
                brandData[i][brandData[i].length - 2]['rank'] = j;
                brandData[i][brandData[i].length - 2]['diff'] = brandData[i][brandData[i].length - 2]['rank'] - brandData[i][brandData[i].length - 1]['rank'];
                j += 1;
            }
        }
        this.brandData = brandData;

        this.showData();
    },
    showData() {
        var brandData = this.brandData,
            orderType = this.state.orderType;
        if (parseInt(orderType) === 1) {
            brandData.sort(function (a1, a2) {
                return parseInt(a1[a1.length - 1].rank) > parseInt(a2[a2.length - 1].rank) ? 1 : -1
            });
        } else if (parseInt(orderType) === 2) {
            brandData.sort(function (a1, a2) {
                return parseInt(a1[a1.length - 1].rank) < parseInt(a2[a2.length - 1].rank) ? 1 : -1
            });
        } else if (parseInt(orderType) === 3) {
            if (brandData[0] && brandData[0].length > 1) {
                brandData.sort(function (a1, a2) {
                    return parseInt(a1[a1.length - 2].diff) < parseInt(a2[a2.length - 2].diff) ? 1 : -1
                });
            }
        } else if (parseInt(orderType) === 4) {
            if (brandData[0] && brandData[0].length > 1) {
                brandData.sort(function (a1, a2) {
                    return parseInt(a1[a1.length - 2].diff) > parseInt(a2[a2.length - 2].diff) ? 1 : -1
                });
            }
        }
        this.setState({ brandData: brandData })
    },
    selectTypeOnChange(value) {
        this.state.TimeType = value;
        this.setState({ TimeType: value })
        this.getAllBrandsFlow();
    },
    onChange(val) {
        Popup.hide();
        this.state.orderType = val[0];
        this.setState({ orderType: val[0] })
        this.getAllBrandsFlow();
    },
    onClick() {
        Popup.show(<SelectNode onClose={() => Popup.hide()} onChange={this.onChange} value={this.state.orderType} />, { animationType: 'slide-up' });
    },
    render() {
        let brandNode = this.state.brandData.map((item) => {
            let diff = '', diffState = 0,
                rank1 = item[item.length - 1].rank,
                rank2 = item[item.length - 2].rank;
            if (rank2 && rank1 && rank1 !== rank2) {
                diff = rank2 - rank1; diffState = diff < 0 ? 1 : 2; diff = Math.abs(diff)
            }
            return <div className="line flex" data-id={item[item.length - 1].AREAID} data-name={item[item.length - 1].AREANAME}>
                <div className="flex-g-1">{item[item.length - 1].AREANAME}</div>
                <div className="flex-col-4">{item[item.length - 1].CDATA}/{item[item.length - 1].per}%</div>
                <div className="flex-col-2">{rank1}/<span className={"diffState" + diffState}>{diff}</span></div>
                <Link className="flex-g-1 text-right link" to={'brandsflowSummary/' + this.props.params.shopId + '/' + item.AREAID}>查看详情{'>'}</Link>
            </div>
        })
        return (
            <div id="brand" >
                <div className="flowContent">
                    <div className="flowHead ">
                        <div className="title flex">
                            <div>品牌排名</div>
                            <div className="date flex-g-1 text-right">{new XDate().toString('yyyy-MM-dd')}</div>
                        </div>
                    </div>
                    <div>
                        <SelectType data={timeData} value={this.state.TimeType} onChange={this.selectTypeOnChange} />
                    </div>
                    <div className="content">
                        <div className="head flex">
                            <div className="flex-g-1">品牌名称</div>
                            <div className="flex-col-4">客流人数/占比</div>
                            <div className="flex-col-3" onClick={this.onClick}>排名/升降</div>
                        </div>
                        {brandNode}
                    </div>
                </div>
            </div>
        );
    }
})

module.exports = Brand;